package sit.mycatalog.web.mbean;

import java.io.IOException;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.apache.commons.io.FilenameUtils;
import org.apache.myfaces.custom.fileupload.UploadedFile;

import org.richfaces.event.FileUploadEvent;
//import org.richfaces.model.UploadedFile;

public class UploadBean {

	private UploadedFile uploadedFile;

	public UploadedFile getUploadedFile() {
		return uploadedFile;
	}

	public void setUploadedFile(UploadedFile uploadedFile) {
		this.uploadedFile = uploadedFile;
	}

	public String uploadFile() {
		try {
		String fileName = FilenameUtils.getName(uploadedFile.getName());
		String contentType = uploadedFile.getContentType();
		byte[] bytes = uploadedFile.getBytes();
		
		System.out.print(bytes.length);

		// Now you can save bytes in DB (and also content type?)

		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(String.format("File '%s' of type '%s' successfully uploaded!", fileName, contentType)));
		} catch(Exception e) {
			e.printStackTrace(System.out);
		}
		
		return "OK";
	}
	
	public void listener(FileUploadEvent event) throws Exception {
		org.richfaces.model.UploadedFile item = event.getUploadedFile();
		System.out.println(item.getData().length);
    }
}
